<%@ page import="com.macrosolution.exdebito.FileDocument" %>
<!DOCTYPE html>
<html>

<head>
	<meta name="layout" content="kickstart" />
	
	<title><g:message code="File Upload" /></title>
	<script type="text/javascript">

	
	
	
	$(document).ready(function(){
		
<%--		pageSetUp();--%>
var  progress = $('myprogress').progressbar();

	

		load_folder();
		$('#add_folder').dialog({
			autoOpen : false,
			position:'top',
			width : 600,
			resizable : true,
			modal : true,
			close:function(){
				$('#docTypeTxt').val('');
				$('#btn_add').button('reset');
				$('#failureAdd').fadeOut();
				}
			
		});

		$('#add_folderPop').click(function() {
			$('#add_folder').dialog('open');
			return false;
	
		});
		$('.tree > ul').attr('role', 'tree').find('ul').attr('role', 'group');
		$('.tree').find('li:has(ul)').addClass('parent_li').attr('role', 'treeitem').find(' > span').attr('title', 'Collapse this branch').on('click', function(e) {
			var children = $(this).parent('li.parent_li').find(' > ul > li');
			if (children.is(':visible')) {
				children.hide('fast');
				$(this).attr('title', 'Expand this branch').find(' > i').removeClass().addClass('fa fa-lg fa-plus-circle');
			} else {
				children.show('fast');
				$(this).attr('title', 'Collapse this branch').find(' > i').removeClass().addClass('fa fa-lg fa-minus-circle');
			}
			e.stopPropagation();
		});	


	});

	function show_files(folder_id,orderby){
		
		${remoteFunction(
				action:'filesInFolder',
				type:'POST',
				onLoading:'spinPage(true);',
				onComplete:'spinPage(false);',
				update: [success: 'filesList', failure: 'daImp'],
				params:'\'folderId=\' + folder_id + \'&order_by=\' + orderby',
				
		)}

	}

	function load_folder(){

		${remoteFunction(
				action:'load_folder',
				type:'POST',
				update: [success: 'folder_tree', failure: 'get'],
				onSuccess:'spinPage(false)',
				onLoading:'spinPage(true);',
				onFailure:'failureLoadPage(XMLHttpRequest,textStatus,errorThrown)',
				onComplete:'spinPage(false)'
				
								
		)}
	}
	

	function delete_files(folder_id){
		${remoteFunction(
				action:'deleteFile',
				type:'POST',
				 update: [success: 'filesList', failure: 'daImp'],
				 onLoading:'spinPage(true);',
				 onComplete:'spinPage(false)',
		       params: '\'folderId=\' + folder_id'
				
		)}

	}

	function fileCancelAlert(idFile){
		$.SmartMessageBox({
			title : "<div class='row'><div class='col-md-2'><i class='fa '></i></div><div class='col-md-10'>Sei Sicuro di voler eliminare questo file?</div>",
			content : "<div class='col-md-2'></div><div class='col-md-10'> <BR/><BR/></div></div>",
			buttons:"[Si],[No]",
			sound:false
		}, function(ButtonPressed, Value) {
			if (ButtonPressed === "No") {
				
			}
			if (ButtonPressed === "Si") {
				${remoteFunction(asynchronous: true,
	 					action:'deleteFile',
						controller:'FileDocument',
						onLoading:'spinPage(true);',
						onComplete:'spinPage(false)',
						params:'\'id=\'+idFile',
						update:[success:'filesList'],
						onFailure:'failureLoadPage(XMLHttpRequest,textStatus,errorThrown)',
						onSuccess:'loadFileNumbers();successAdd("File eliminato correttamente")'
						
						)} 
			}
			});
	}

	function folderCancelAlert(idFolder){
		$.SmartMessageBox({
			title : "<div class='row'><div class='col-md-2'><i class='fa '></i></div><div class='col-md-10'>Sei Sicuro di voler eliminare questa cartella e tutti i file contenuti?</div>",
			content : "<div class='col-md-2'></div><div class='col-md-10'> <BR/><BR/></div></div>",
			buttons:"[Si],[No]",
			sound:false
		}, function(ButtonPressed, Value) {
			if (ButtonPressed === "No") {
				
			}
			if (ButtonPressed === "Si") {
				${remoteFunction(asynchronous: true,
	 					action:'deleteFolder',
						controller:'FileDocument',
						onLoading:'spinPage(true);',
						onComplete:'spinPage(false)',
						params:'\'folderId=\'+idFolder',
						update:[success:'folder_tree'],	
						onSuccess:'emptyFileList();successAdd("Cartella Eliminata correttamente")',
						onFailure:'failureLoadPage(XMLHttpRequest,textStatus,errorThrown)'
						)} 
			}
			});
	}
		function  emptyFileList(){
			$('#filesList').empty();

		}

	
	
	function cliccable(idit){

		var idd = idit+'it';
		$('#2it').addClass('bg-color-green');
	}

	function spinPage(onoff){

		if(onoff){
			$('#spinPage').fadeIn();
		
		}else{
			$('#spinPage').fadeOut();
		}
	
	}

	function failAdd(){

		$('#btn_add').button('reset');
		$('#failureAdd').fadeIn();
	}
	function successAdd(text){

		$('#docTypeTxt').val('');
		$('#btn_add').button('reset');
		$('#add_folder').dialog('close');
		$('#failureAdd').fadeOut();
		$.smallBox({
			title : text,
			color : "#3F8DBF",
			sound:true,
			timeout: 3000
		});
	}

	function failureLoadPage(a,b,c){
		$.smallBox({
			title : a.responseText,
			color : "#a90329",
			sound:true,
			timeout: 3000
		});

	}


	function uploadAj(){

		var folder = $('#documentType').val();
		var comments = $('#comments').val();
		var data = new FormData();
		data.append("documentType", folder);
		data.append("comments", comments);
		data.append("file", fileUtil.files[0]);

		spinPage(true);
		pleaseWait();
		var myXHR=$.ajax({
			 xhr: function()
			  {
			    var xhr = new window.XMLHttpRequest();
			    //Upload progress
			    xhr.upload.addEventListener("progress", function(evt){
			      if (evt.lengthComputable) {
				      
			        var percentComplete = evt.loaded / evt.total;
			        //Do something with upload progress
			        var cento = percentComplete*100;
<%--			        $('#myprogress').css('width', percentComplete+'%').attr('aria-valuenow', percentComplete);--%>
			        $('#myprogress').attr('aria-valuenow', cento);
			        $('#myprogress').css('width', cento + '%');

						$("#myprogress").html(cento.toFixed(0)+"%");
				   }
			    }, false);
			    //Download progress
			    xhr.addEventListener("progress", function(evt){
			      if (evt.lengthComputable) {
			        var percentComplete = evt.loaded / evt.total;
			        //Do something with download progress
			        $('.progress-bar').css('width', percentComplete+'%').attr('aria-valuenow', percentComplete);
					$("myprogress").html(percentComplete);
				   }
			    }, false);
			    return xhr;
			  },
			
			url: "${createLink(action:'uploadAj')}",
		    type: 'POST',
		    data: data,
		    cache: false,
		     
		    processData: false, // Don't process the files
		    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
		    
		    success: function(data, textStatus, jqXHR)
		    {
		       if(typeof data.error === 'undefined')
		        {
		                // Success so call function to process the form
		                successUpload(data,folder);
		                loadFileNumbers();
		                resetafterUp();
		                
				        
		            }
		            else
		            {
		                // Handle errors here
		                
		                console.log('ERRORS: ' + data.error);
		            }
		        },
		        error: function(jqXHR, textStatus, errorThrown)
		        {
		            // Handle errors here
		            console.log('ERRORS: ' + textStatus);
		            
		            failureUpload(jqXHR,textStatus,errorThrown)
		            spinPage(false);
		            resetafterUp()
		            // STOP LOADING SPINNER
		        },
		        complete: function()
		        {
					spinPage(false);
					resetafterUp();
		            // STOP LOADING SPINNER
		        }
		    });
		
		

		

	}
	
	function completeHandler(event){
		console.log( event.target.responseText);
		
	}

	function successUpload(data,folder){

		$.smallBox({
			title : data,
			color : "#3F8DBF",
			sound:false,
			timeout: 3000
		});
		show_files(folder);
		
	}
	function failureUpload(a,b,c){
		
		$.smallBox({
			title : a.responseText,
			color : "#a90329",
			sound:false,
			timeout: 3000
		});

	}

	function showfDetails(fileId){

		${remoteFunction(
			action:'showFileDetail',
			type:'POST',
			update: [success: 'file_d', failure: 'get'],
		  	params: '\'fileId=\' + fileId',
			onSuccess:'spin(fileId,false);$("#fdutil_modal").modal()',
			onLoading:'spin(fileId,true);',
			onFailure:'showCancelResponse(XMLHttpRequest,textStatus,errorThrown)',
			onComplete:'spin(fileId,false)'
		)}

		

	}

	function spin(fileId,onoff){
		if(onoff){
			$('#spin_'+fileId).fadeIn();
		}else{
			$('#spin_'+fileId).fadeOut();
		}	
	}

	function showuploadpp(){

		${remoteFunction(
			action:'showuploadp',
			type:'POST',
			update: [success: 'uploadpp', failure: 'get'],
		  	onSuccess:'spinPage(false);$("#fileUpload_modal").modal()',
			onLoading:'spinPage(true);',
			onFailure:'showCancelResponse(XMLHttpRequest,textStatus,errorThrown)',
			onComplete:'spinPage(false);'
		)}

		

	}

	function pleaseWait(){
		$("#btnUpload").button('loading');
		$('#progressBox').fadeIn();
		$('#upcloseBtn').prop('disabled', true);
		$('#upcloseBtn').prop('disabled', true);
		$('#fileUtil').prop('disabled',true);
		$('#documentType').prop('disabled',true);
		$('#comments').prop('disabled',true);
	}
	function resetafterUp(){
		$('#progressBox').hide();
		$("#btnUpload").button('reset');
		$('#upcloseBtn').prop('disabled', false);
		$('#upcloseBtn').prop('disabled', false);
		$('#myprogress').attr('aria-valuenow', 0);
        $('#myprogress').css('width', 0 + '%');
        $('#fileUtil').prop('disabled',false);
        $('#documentType').prop('disabled',false);
        $('#comments').prop('disabled',false);
	}
	
	</script>
</head>

<body>		
	

			<!-- RIBBON -->
			<div id="ribbon">

				<span class="ribbon-button-alignment"> 
					
				</span>

				<!-- breadcrumb -->
				<ol class="breadcrumb">
					<li>Home</li><li>Gestione File</li>
				</ol>
				<!-- end breadcrumb -->

				

			</div>
			<!-- END RIBBON -->

			<!-- MAIN CONTENT -->
<div id="content">
	<g:if test="${flash.message }">
			<div class="row">
				<div class="col col-md-6">
					<div class="alert alert-success fade in">
						<button class="close" data-dismiss="alert">
							×
						</button>
						<i class="fa-fw fa fa-check"></i>
						<strong><g:message code="${flash.message}"/></strong> 
					</div>
				</div>
			</div>
		</g:if>
	<div class="row">
		
		<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6" >
			<h1 class="page-title txt-color-blueDark">
				<i class="fa fa-cloud fa-fw "></i> Gestione File <span>>
					Home </span>
					
			</h1>
			<div class="row">
			
				<sec:ifAnyGranted roles="ROLE_ADMIN,ROLE_AMM">
<%--				<div class="col-xs-12 col-sm-6 col-md-10 col-lg-5 " >--%>
<%--					<a data-target="#fileUpload_modal" data-toggle="modal" class="btn btn-default"><i--%>
<%--						class="fa fa-file txt-color-green"></i> Aggiungi un File</a>--%>
<%--	--%>
<%--				</div>--%>
				<div class="col-xs-12 col-sm-6 col-md-10 col-lg-5 " >
					<a onclick="showuploadpp()"  class="btn btn-default"><i
						class="fa fa-file txt-color-green"></i> Aggiungi un File</a>
	
				</div>
				
				<div class="col-xs-12 col-sm-6 col-md-4 col-lg-5" >
					<a id="add_folderPop" class="btn btn-default"><i
						class="fa fa-folder txt-color-yellow"></i> Aggiungi una Cartella</a>
	
				</div>
				<div class="col-xs-12 col-sm-6 col-md-4 col-lg-2 " >
					
					<i id="spinPage" class="fa fa-gear fa-2x fa-spin pull-right" ></i>
					
				</div>
	
				</sec:ifAnyGranted>
			</div>

			<div id="folder_tree" class="col col-md-12">
					
					
			
			
			</div>
			
		</div>
		
		<div id="filesList"  class="col-xs-12 col-sm-6 col-md-6 col-lg-6" >
			
			
		
		
		</div>
	
	</div>
	
</div>

<%--<g:render template="uploadpopup"></g:render>--%>

<div id="uploadpp">
	<g:render template="uploadpopup"></g:render>
</div>


<g:render template="add_folder"></g:render>
<div id="file_d">
	<g:render template="filedetailpopup"></g:render>
</div>
			
</body>

</html>